package com.zhang.demoaidl;

import com.zhang.demoaidl.R;

import aidl.IAidlserver;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

	private TextView show;
	private Button callaidl,btnset;
	private IAidlserver maidlserver;
	private String TAG = "DemoAidlserver---->";
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			maidlserver = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			maidlserver = IAidlserver.Stub.asInterface(service);

			try {
				maidlserver.setString("jiangi");
				String mtext = maidlserver.sayhello() + "\n" + maidlserver.getbook().getname() + "\n"
						+ maidlserver.getbook().getprice();
				show.setText(mtext);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};

	
	public class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			
		}
		
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		show = (TextView) findViewById(R.id.show);
		callaidl = (Button) findViewById(R.id.callaidl);
		btnset = (Button) findViewById(R.id.btnset);

	}

	@Override
	protected void onResume() {
		super.onResume();
		
		callaidl.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent service = new Intent("aidl.DemoIAidlserver");
				bindService(service, mConnection, BIND_AUTO_CREATE);
				Log.e(TAG, "MainActivity.....bindService");
			}
		});
		
		btnset.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					maidlserver.setString("setsomething");
					String mtext = maidlserver.sayhello() + "\n" + maidlserver.getbook().getname() + "\n"
							+ maidlserver.getbook().getprice();
					show.setText(mtext);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});
	}

}
